package com.example.profile_encryption.config;

import lombok.extern.slf4j.Slf4j;


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Formatter;

/**
 * HMAC(Hash Message Authentication Code，散列消息鉴别码)
 * 使用一个密钥生成一个固定大小的小数据块，即MAC，并将其加入到消息中，然后传输。接收方利用与发送方共享的密钥进行鉴别认证，
 */

@Slf4j
public class SHAConfig {
    private static final String HASH_ALGORITHM = "HmacSHA256";

    //加密接口
    public static String getAfterSha(String str,String key){
        String afterShaString = "";
        try {
            afterShaString = hashMac(str, key);
        } catch (SignatureException e) {
            log.error("获取加密字符串失败,",e);
        }
        return afterShaString;
    }



    /**
     * hashMac Method that encrypt the data and convert into hex values...  HMAC加密
     * @param text          消息
     * @param secretKey     密钥
     * @return              加密后字符串
     * @throws SignatureException
     */
    public static String hashMac(String text, String secretKey)
            throws SignatureException {
        try {
            Key sk = new SecretKeySpec(secretKey.getBytes(), HASH_ALGORITHM);
            Mac mac = Mac.getInstance(sk.getAlgorithm());
            mac.init(sk); // 初始化mac
            final byte[] hmac = mac.doFinal(text.getBytes());
            return toHexString(hmac);
        } catch (NoSuchAlgorithmException e1) {
            throw new SignatureException(
                    "error building signature, no such algorithm in device "
                            + HASH_ALGORITHM);
        } catch (InvalidKeyException e) {
            throw new SignatureException(
                    "error building signature, invalid key " + HASH_ALGORITHM);
        }
    }


    //toHexString Method...
    public static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);

        Formatter formatter = new Formatter(sb);
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }

        return sb.toString();

    }
}
